package study.nosql.mongodb.support.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SaveEventListener extends AbstractMongoEventListener<Object> {

    @Override
    public void onBeforeConvert(BeforeConvertEvent<Object> event) {
        //
        Object source = event.getSource();
        log.info(">>>>>> {}", source.toString());
        event.getCollectionName();
//        if (source != null) {
//            ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
//                @Override
//                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
//                    ReflectionUtils.makeAccessible(field);
//                    // 如果字段添加了我们自定义的AutoIncKey注解
//                    if (field.isAnnotationPresent(AutoIncKey.class)) {
//                        // 设置自增ID
//                        field.set(source, getNextId(source.getClass().getSimpleName()));
//                    }
//                }
//            });
//        }

    }

//    private Integer getNextId(String collName) {
//        Query query = new Query(Criteria.where("collName").is(collName));
//        Update update = new Update();
//        update.inc("incId", 1);
//        FindAndModifyOptions options = new FindAndModifyOptions();
//        options.upsert(true);
//        options.returnNew(true);
//        IncInfo inc = mongodb.findAndModify(query, update, options, IncInfo.class);
//        return inc.getIncId();
//    }
}
